/* eslint-disable react/jsx-indent */
/* eslint-disable no-nested-ternary */
import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import qs from 'qs';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Card,
  Row,
  Col,
  Form,
  Input,
  Button,
  message,
  Icon,
  Checkbox,
  Table,
  Tag,
  Select,
  Modal,
  Radio,
  Spin,
  Upload,
  Tabs,
  Tooltip,
  Drawer,
  Pagination
} from 'antd';
import Custom from './custom.js';
import CustomNew from './customNew';
import download from '@/utils/download';
import { routerRedux } from 'dva/router';
import axios from 'axios';
import BackRouter from '@/pages/CapacityStudy/KnowledgeSmartMaintenance/backRouter';
import deleteimg from '@/assets/buttonimg/delete.png';
const { TabPane } = Tabs;
const FormItem = Form.Item;
const Search = Input.Search;
const InputGroup = Input.Group;
import styles from './index.less';
const { Option } = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
import pen from '../../../assets/icons/bi.png';
import ljx from '../../../assets/icons/垃圾箱.png';

class EnumerableNew extends Component {
  constructor(props) {
    super(props);
    this.state = {
      close: true,
      disabled: true,
      name: this.props.history.location.params
        ? this.props.history.location.params.id.name
        : decodeURIComponent(window.location.href.split('?')[1].split('&')[1]),
      okid: this.props.history.location.params
        ? this.props.history.location.params.id.id
        : decodeURIComponent(window.location.href.split('?')[1].split('&')[0]),
      okname: this.props.history.location.params
        ? this.props.history.location.params.id.name
        : decodeURIComponent(window.location.href.split('?')[1].split('&')[1]),
      mockValue: '',
      pageA: 1,
      limit: 10,
      itemNames: '',
      totab: '',
      dataSource2: [],
      listday: [],
      itemId: '',
      formatA: '',
      formatB: '',
      formatC: '',
      listday: [],
      showModel1: false,
      showModel2: false,
      tcxModel: false,
      login: true,
      fileList: [],
      uploading: false,
      uploadId: {
        dictId: this.props.history.location.params
          ? this.props.history.location.params.id.id
          : decodeURIComponent(window.location.href.split('?')[1].split('&')[0]),
      },
    };
  }

  componentDidMount() {
    // console.log(this.props.history.location.params.id)

    // 新增部分
    if (window.location.href.split('?')[1]) {
      this.setState({ okid: window.location.href.split('?')[1].split('&')[0] }, () => {
        this.fetchb();
      });
    } else {
      this.setState(
        {
          okid: this.props.history.location.params.id.id,
          okname: this.props.history.location.params.id.name,
          uploadId: { dictId: this.props.history.location.params.id.id },
        },
        () => {
          this.fetchb();
        }
      );
    }
  }

  fetchb = () => {
    this.setState({
      login: true,
    });

    const { dispatch, currentUser } = this.props;
    const { okid, pageA, limit, itemNames } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customDictionary/enumList',
        payload: { dictId: okid, page: pageA, limit, itemNames },
        callback: res => {
          console.log('componentWillMount', res);
          let a = res.list;
          a.map((item, index) => {
            item['key'] = index;
          });
          this.setState({
            dataSource2: a,
            listday: a,
            totab: res.total,
            login: false,
          });
        },
      });
    });
  };

  // 词典名称修改
  textInput = () => {
    const { getFieldDecorator } = this.props.form;
    return (
      <div style={{marginLeft:20}} className={styles.flexcen}>
        <Form layout="inline" onSubmit={this.handleSubmit}>
          <FormItem label="实体名称">
            {getFieldDecorator('namecid', {
              initialValue: '',
            })(
              <div>
                <Input
                  defaultValue={this.state.name}
                  disabled={this.state.disabled}
                  onPressEnter={this.saveChanges}
                  onChange={this.namegai}
                />
              </div>
            )}
          </FormItem>
          {this.state.disabled === true ? (
            <span>
              <Icon onClick={this.modifyClick} className={styles.fleximg} type="edit" />
            </span>
          ) : (
            <span>
              <Icon onClick={this.bcClick} className={styles.fleximg} type="check" />
            </span>
          )}
        </Form>
      </div>
    );
  };

  returnButton = () => {
    return <BackRouter style={{ float: 'right' }} pathname="/basic/customDictionary" />;
  };

  namegai = e => {
    console.log(e.target.value);
    this.setState({ mockValue: e.target.value });
  };

  // 字典名称显示或隐藏
  modifyClick = () => {
    this.setState({
      disabled: false,
    });
  };

  bcClick = () => {
    if (this.state.mockValue === '') {
      // message['warning']('未修改')

      this.setState({
        disabled: true,
      });
      console.log(this.state.okid);
      const { dispatch } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'customDictionary/fetche',
          payload: { dictId: this.state.okid, dictName: this.state.okname },
          callback: res => {
            console.log('componentWillMount', res);
            if (res.status === true) {
              message['success'](`${res.msg}`);
            }
            if (res.status === false) {
              message['error'](`${res.msg}`);
            }
          },
        });
      });
    } else {
      this.setState({
        disabled: true,
      });
      // message['success']('修改成功')
      // 可枚举页 修改词典
      console.log(this.state.okid);
      const { dispatch } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'customDictionary/fetche',
          payload: { dictId: this.state.okid, dictName: this.state.mockValue },
          callback: res => {
            console.log('componentWillMount', res);
            if (res.status === true) {
              message['success'](`${res.msg}`);
            }
            if (res.status === false) {
              message['error'](`${res.msg}`);
            }
          },
        });
      });
    }
  };

  onChangeB = val => {
    // 页数选择
    console.log(val);
    this.setState({ pageA: val }, () => {
      this.fetchb();
    });
  };

  // 每页显示多少条数据
  onShowSizeChangeB = (current, pageSize) => {
    console.log(current, pageSize);
    this.setState({ pageA: current, limit: pageSize }, () => {
      this.fetchb();
    });
  };

  // 子页面修改内容
  enumeration = () => {
    this.props.form.setFields({ coreword: '' });
    this.props.form.setFields({ synonym: '' });
    this.setState({
      formatA: '',
      formatB: '',
      showModel2: true,
    });
  };

  // 子页面
  coreWord = () => {
    let userInfo = this.props.form.getFieldsValue(); // 获取数据
    this.props.form.validateFields((err, values) => {
      // 校验方法
      let userInfo = this.props.form.getFieldsValue(); // 获取数据
      if (!err) {
        console.log(userInfo);
        if (userInfo.coreword !== '') {
          const { dispatch, currentUser } = this.props;
          this.reqRef = requestAnimationFrame(() => {
            dispatch({
              type: 'customDictionary/fetchf',
              payload: {
                dictId: this.state.okid,
                itemWord: userInfo.coreword,
                itemSynWords: userInfo.synonym,
                itemId: this.state.itemId,
              },
              callback: res => {
                console.log('字页增加内容', res);
                if (!res.code) {
                  message.success(`${res.msg}`);
                  this.setState(
                    {
                      showModel2: false,
                      pageA: 1,
                      itemId: '',
                    },
                    () => {
                      this.fetchb(
                        this.state.okid,
                        this.state.pageA,
                        this.state.pageSizeA,
                        this.state.ziyevalue
                      );
                    }
                  );
                } else {
                  this.setState({
                    showModel2: true,
                  });
                }
              },
            });
          });
        } else {
          message['warning']('请添加核心词');
        }
      }
    });
  };

  handleDeleteA = item => {
    console.log('修改内容', item);
    this.props.form.setFields({ coreword: '' });
    this.props.form.setFields({ synonym: '' });
    this.setState({
      formatA: item.word,
      formatB: item.synWords.join(','),
      itemId: item.id, // _id
      showModel2: true,
    });
  };

  fromDeletes = item => {
    console.log('item', item);
    const text = item.isUse
      ? '该自定义实体正在被使用中，删除后将影响机器人的正常问答，是否确定删除'
      : '确定删除吗？';
    Modal['confirm']({
      title: '删除任务',
      content: text,
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        const { dispatch } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'customDictionary/fetchg',
            payload: { dictId: this.state.okid, itemId: item.id }, // _id
            callback: res => {
              console.log('删除', res);
              this.fetchb();
              if (!res.code) {
                message.success(`执行成功！`);
              }
            },
          });
        });
      },
      onCancel() {
        console.log('onCancel');
      },
    });
  };

  answerDetail = () => {
    if (this.state.totab === 0) {
      message.error('空列表无法导出！');
    } else {
      const { dispatch, currentUser } = this.props;
      const { itemNames } = this.state;
      let object = {};
      console.log(this.state);
      object.dictId = this.state.uploadId.dictId;
      object.dictItemNames = this.state.itemNames;
      dispatch({
        type: 'customDictionary/exporta',
        payload: object,
        callback: res => {
          let filename = decodeURIComponent(
            res.requestRes.headers.get('Content-Disposition').split('=')[1]
          );
          download.byBlob(res.fileBlob, filename);
        },
      });
    }
  };

  toLeadt = () => {
    this.setState({ tcxModel: true });
  };

  handleUpFile = info => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map(file => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    if (fileList[0].size > 2000000) {
      message.error('上传文件超出2M');
      this.setState({ fileList: [] });
    } else {
      this.setState({ fileList });
    }
  };

  uploadFile = data => {
    console.log(data);
    const token =
      JSON.parse(window.localStorage.getItem('currentUser')) == undefined
        ? ''
        : JSON.parse(window.localStorage.getItem('currentUser')).token;
    const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId")) ;
    axios
      .post('/cloud/new/basic/dict/import', data, {
        method: 'post',
        processData: false,
        headers: { 'Content-Type': 'application/json', token: token,'robotId':robotId },
      })
      .then(res => {
        this.setState(
          {
            uploading: false,
          },
          () => {
            if (res.data.code) {
              this.fetchb();
              return message.error(res.data.msg);
            } else {
              this.fetchb();
              this.setState(
                {
                  tcxModel: false,
                  visible: false,
                  fileList: [],
                },
                () => {
                  if (res.data.msg) {
                    message.success(res.data.msg);
                  } else {
                    message.success('导入成功');
                  }
                }
              );
            }
          }
        );
      })
      .catch(error => {
        message.error('导入失败请稍等再试');
      });
  };

  businessWayA = () => {
    const { fileList, uploadId } = this.state;
    console.log(uploadId);
    const formData = new FormData();
    fileList.forEach(file => {
      console.log(file);
      formData.append('file', file.originFileObj);
      formData.append('dictId', uploadId.dictId);
    });
    this.setState({
      uploading: true,
    });
    this.uploadFile(formData);
  };

  handleCancel = () => {
    this.setState({ tcxModel: false, uploading: false, fileList: [] });
  };

  // 下载模版
  dictTemp = () => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'customDictionary/templateA',
      payload: {},
      callback: res => {
        let filename = decodeURIComponent(
          res.requestRes.headers.get('Content-Disposition').split('=')[1]
        );
        download.byBlob(res.fileBlob, filename);
      },
    });
  };

  Tooltipzdy = () => {
    return (
      <div>
        {`添加/编译实体`}
        <span style={{ marginLeft: 12, paddingTop: 3 }}>
          <Tooltip
            placement="top"
            title="核心词：必填。不可带有标点符号和各种括号。词典名称是该词典下所有核心词的统称。同义词：核心词的同义词。选填。同义词之间以中英文逗号隔开。"
            arrowPointAtCenter
          >
            <Icon style={{ fontSize: 14 }} type="info-circle" />
          </Tooltip>
        </span>
      </div>
    );
  };

  onClose = () => {
    this.setState({
      close: false,
    });
    setTimeout(() => {
      const { dispatch } = this.props;
      dispatch(
        routerRedux.push({
          pathname: '/basic/customDictionary',
        })
      );
    }, 300);
  };

  render() {
    const columns1 = [
      {
        title: <FormattedMessage id="app.customDictionary.core-word" defaultMessage="coreWord" />,
        width: 'calc(30vw)',
        dataIndex: 'word',
      },
      {
        title: <FormattedMessage id="app.customDictionary.core-agreed" defaultMessage="agreed" />,
        width: 'calc(30vw)',
        dataIndex: 'synWords',
        render: synWords => (
          <span>
            {synWords.map((tag, index) => {
              let color = index % 2 == 1 ? '#5092e1' : '#87d3ac';
              return (
                <Tag style={{ marginBottom: 2 }} color={color} key={tag}>
                  {tag}
                </Tag>
              );
            })}
          </span>
        ),
      },
      {
        title: <FormattedMessage id="app.customDictionary.operation" defaultMessage="operation" />,
        dataIndex: 'sex',
        render: (text, item) => {
          return (
            <div className={styles.pb}>
              <div
                className={styles.buttongl}
                onClick={text => {
                  this.handleDeleteA(item);
                }}
              >
                <img style={{ marginRight: 5 }} src={pen} />
                <span style={{ marginBottom: 1 }}>
                  <FormattedMessage id="app.customDictionary.edit" defaultMessage="Edit" />
                </span>
              </div>
              <div
                style={{ marginLeft: 10, background: '#e8313b' }}
                className={styles.buttongl}
                onClick={text => {
                  this.fromDeletes(item);
                }}
              >
                <img src={deleteimg} style={{ marginRight: 5 }} />
                <span style={{ marginBottom: 1 }}>
                  {' '}
                  <FormattedMessage id="app.customDictionary.out" defaultMessage="out" />
                </span>
              </div>
            </div>
          );
        },
      },
    ];

    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        // 文字
        xs: 24,
        sm: 4,
      },
      wrapperCol: {
        // 输入框
        xs: 24,
        sm: 20,
      },
    };
    const headData = { token: JSON.parse(window.localStorage.getItem('currentUser')).token };
    const { uploading, fileList } = this.state;
    const props1 = {
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      accept: '.xlsx',
      fileList,
      onChange: this.handleUpFile,
    };
    return (
      <Drawer
        className="zdyset"
        title={
          <span  onClick={this.onClose} style={{cursor:'pointer'}}>
             <Icon type="arrow-left" style={{ marginRight: 20 }} />
            可枚举实体
          </span>
        }
        placement="right"
        closable={false}
        onClose={this.onClose}
        visible={this.state.close}
        width="calc(100vw - 245px)"
        destroyOnClose
      >
        <div>
          {this.textInput()}
          {/* {this.returnButton()} */}
          {/* {this.returnButton()} */}
          <div className={styles.fromColumn}>
            <span style={{marginLeft:20}} className="buttonYs">
              <Button onClick={this.enumeration} icon="plus">
                <FormattedMessage id="app.customDictionary.add" defaultMessage="add" />
              </Button>
            </span>
            <span className="buttonYs">
              <Button icon="arrow-down" onClick={this.toLeadt}>
                导入
              </Button>
            </span>
            <span className="buttonYs">
              <Button icon="arrow-right" onClick={this.answerDetail}>
                导出
              </Button>
            </span>
            <span style={{marginRight:24}} className={styles.right}>
              <Search
                placeholder="请输入搜索内容"
                onSearch={value => {
                  console.log(value);
                  this.setState({ itemNames: value, pageA: 1 }, () => {
                    this.fetchb();
                  });
                }}
                style={{ width: 323 }}
              />
            </span>
          </div>
          <Spin spinning={this.state.login}>
          <div className={styles.dabj} style={{ padding: '0px 20px' }}>
          <div className={styles.border}>
            <Table // 可枚举类型
              className="zdyTable"
              // style={{ padding: '20px 0px 0px 0px' }}
              columns={columns1}
              dataSource={this.state.dataSource2} // 数据
              onChange={this.handleChange}
              pagination={false}
            />
            </div>
            </div>
          </Spin>
          <Pagination
            style={{ textAlign: 'center', marginTop: 20 }}
            total={this.state.totab}
            pageSize={this.state.limit} // 显示几条一页
            current={this.state.pageA} // 当前页
            showSizeChanger={true} // 是否显示可以设置几条一页的选项
            showQuickJumper={true}
            onChange={this.onChangeB}
            onShowSizeChange={this.onShowSizeChangeB}
            showTotal={() => `共 ${this.state.totab} 条`}
          />
          <Modal
            className="modelZdy"
            title={this.Tooltipzdy()}
            visible={this.state.showModel2}
            okText={<FormattedMessage id="app.customDictionary.save" />}
            cancelText={<FormattedMessage id="app.customDictionary.cancel" />}
            onCancel={() => {
              this.setState({
                showModel2: false,
              });
            }}
            onOk={this.coreWord} // 确定方法开出去
          >
            <Form layout="horizontal">
              <FormItem
                label={<FormattedMessage id="app.customDictionary.core-word" />}
                onSubmit={this.coreWord}
                {...FormItemLayont}
              >
                {getFieldDecorator('coreword', {
                  initialValue: `${this.state.formatA}`,
                })(<Input />)}
              </FormItem>
              <FormItem
                label={<FormattedMessage id="app.customDictionary.core-agreed" />}
                {...FormItemLayont}
              >
                {getFieldDecorator('synonym', {
                  initialValue: `${this.state.formatB}`,
                })(
                  <TextArea
                    placeholder="请输入同义词名称，可填写多个，请以中英文逗号分隔"
                    autosize={{
                      minRows: 4,
                      maxRows: 6,
                    }}
                  />
                )}
              </FormItem>
            </Form>
          </Modal>
          <Modal
            className="modelZdy"
            width={550}
            title="上传实体"
            visible={this.state.tcxModel}
            footer={[
              <Button key="back" onClick={this.handleCancel}>
                取消
              </Button>,
              <Button
                key="submit"
                type="primary"
                loading={uploading}
                disabled={fileList.length === 0}
                onClick={this.businessWayA}
              >
                {uploading ? '导入中' : '开始导入'}
              </Button>,
            ]}
            onCancel={() => {
              this.setState({ tcxModel: false, uploading: false, fileList: [] });
            }}
          >
            <Form layout="horizontal">
              <FormItem label="选择文件" {...FormItemLayont}>
                <Upload {...props1} fileList={this.state.fileList}>
                  <Button>
                    <Icon type="upload" /> 选择文件
                  </Button>
                </Upload>
              </FormItem>
              <FormItem label="上传规则" {...FormItemLayont}>
                <div className={styles.frame}>
                  <div>
                    <span>• 请按照模板中的示例格式进行编辑上传：</span>{' '}
                    <span onClick={this.dictTemp} className={styles.template}>
                      下载xlsx模版
                    </span>
                  </div>
                  <div>
                    <span>•上传文件格式需要为“.xlsx”类型的Excel文件</span>
                  </div>
                  <div>
                    <span>• 导入的实体数据将覆盖现有数据，请谨慎操作</span>
                  </div>
                </div>
              </FormItem>
            </Form>
          </Modal>
        </div>
      </Drawer>
    );
  }
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(EnumerableNew));
